﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;

namespace Script_Text_Editor_WPF_Edition
{
    class FrameworkSupport
    {
        /// <summary>
        /// Get a framework's child by its name
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="referenceElement"></param>
        /// <returns></returns>
        public static T GetFrameworkElementByName<T>(FrameworkElement referenceElement) where T : FrameworkElement
        {
            FrameworkElement child = null;
            for (Int32 i = 0; i < VisualTreeHelper.GetChildrenCount(referenceElement); i++)
            {
                child = VisualTreeHelper.GetChild(referenceElement, i) as FrameworkElement;
                System.Diagnostics.Debug.WriteLine(child);
                if (child != null && child.GetType() == typeof(T))
                { break; }
                else if (child != null)
                {
                    child = GetFrameworkElementByName<T>(child);
                    if (child != null && child.GetType() == typeof(T))
                    {
                        break;
                    }
                }
            }
            return child as T;
        }

        /// <summary>
        /// Get a framework's parent by its name
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="referenceElement"></param>
        /// <returns></returns>
        public static T GetFrameworkParentByName<T>(FrameworkElement referenceElement) where T : FrameworkElement
        {
            FrameworkElement parent = VisualTreeHelper.GetParent(referenceElement) as FrameworkElement;
            System.Diagnostics.Debug.WriteLine(parent);
            if (parent != null)
            {
                if (parent.GetType() == typeof(T))
                    return parent as T;
                else
                {
                    parent = GetFrameworkParentByName<T>(parent);
                    if (parent.GetType() == typeof(T))
                        return parent as T;
                }
            }
            return parent as T;
        }
    }
}